package org.kepler.chat.api.infra.security.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.bigdata.frame.util.Validate;
import org.kepler.chat.api.infra.constant.Constants;
import org.kepler.chat.api.infra.util.ErrorCode;
import org.kepler.chat.api.infra.security.exceptions.JwtBadCredentialsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * RestLoginProcessingFilter
 * 
 * @author ake
 *
 * Aug 3, 2016
 */
public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingFilter {
    private static Logger logger = LoggerFactory.getLogger(RestLoginProcessingFilter.class);

    private final AuthenticationSuccessHandler successHandler;
    private final AuthenticationFailureHandler failureHandler;

    private final ObjectMapper objectMapper;
    
    public RestLoginProcessingFilter(String defaultProcessUrl, AuthenticationSuccessHandler successHandler,
                                     AuthenticationFailureHandler failureHandler, ObjectMapper mapper) {
        super(defaultProcessUrl);
        this.successHandler = successHandler;
        this.failureHandler = failureHandler;
        this.objectMapper = mapper;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        // loginFlag 登录标识  1：员工登录；2：客户登录
        String loginFlag = request.getParameter("loginFlag");
        loginFlag = Validate.isEmpty(loginFlag) ? Constants.LOGINFLAG_USER : loginFlag;
        UsernamePasswordAuthenticationToken token = null;
        if(Constants.LOGINFLAG_USER.equals(loginFlag)){
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
                throw new JwtBadCredentialsException(ErrorCode.PARM_USERNAME_OR_PASSWORD_MISS);
            }
//            String captchaId = request.getParameter("captchaId");
//            String vercode = request.getParameter("vercode");
//            if (StringUtils.isBlank(vercode)) {
//                throw new JwtBadCredentialsException(ErrorCode.PARM_CAPTCHA_MISS);
//            }
//            String cacheKey = GlobalStatic.DEFAULT_CAPTCHA_PARAM + ":"+ captchaId;
//            System.out.println("get cacheKey = " + cacheKey);
//            String captcha = JedisUtils.get(cacheKey);
//            if(null == captcha){
//                throw new JwtBadCredentialsException(ErrorCode.PARM_CAPTCHA_ERROR);
//            }
//            if(!captcha.equalsIgnoreCase(vercode)){
//                throw new JwtBadCredentialsException(ErrorCode.PARM_CAPTCHA_INPUT_ERROR);
//            }
            token = new UsernamePasswordAuthenticationToken(loginFlag+"-"+username, password);
        }
        if(Constants.LOGINFLAG_CUSTOMER.equals(loginFlag)){
            String phone = request.getParameter("phone");
            String channelCode = request.getParameter("channelCode");
            String password = request.getParameter("password");
            if (StringUtils.isBlank(phone)) {
                throw new JwtBadCredentialsException(ErrorCode.PARAM_PHONE_MISS);
            }
            if (StringUtils.isBlank(password)) {
                throw new JwtBadCredentialsException(ErrorCode.PARAM_PASSWORD_MISS);
            }
            if (StringUtils.isBlank(channelCode)) {
                throw new JwtBadCredentialsException(ErrorCode.PARAM_CHANNELCODE_MISS);
            }
            token = new UsernamePasswordAuthenticationToken(loginFlag+"-"+phone+"-"+channelCode, password);
        }
        return this.getAuthenticationManager().authenticate(token);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication authResult) throws IOException, ServletException {
        successHandler.onAuthenticationSuccess(request, response, authResult);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException failed) throws IOException, ServletException {
        SecurityContextHolder.clearContext();
        failureHandler.onAuthenticationFailure(request, response, failed);
    }
}
